<template>
  <div class="order-management">
    <h2>订单管理</h2>

    <!-- 筛选区域 -->
    <div class="filters">
      <input v-model="search" type="text" placeholder="搜索订单或客户" />
      <select v-model="statusFilter">
        <option value="">所有状态</option>
        <option v-for="(label, key) in statusLabels" :key="key" :value="key">{{ label }}</option>
      </select>
    </div>

    <!-- 订单列表 -->
    <table>
      <thead>
      <tr>
        <th>订单编号</th>
        <th>客户姓名</th>
        <th>商品图片</th>
        <th>商品名称</th>
        <th>交易数量</th>
        <th>交易总金额</th>
        <th>交易时间</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="order in filteredOrders" :key="order.id">
        <td>{{ order.id }}</td>
        <td>{{ order.customer }}</td>
        <td>
          <img
              v-if="order.productImage"
              :src="order.productImage"
              alt="商品图片"
              class="product-image"
          />
          <span v-else>暂无图片</span>
        </td>
        <td>{{ order.goodsName }}</td>
        <td>{{ order.tradeAmount }}</td>
        <td>¥{{ order.totalPrice.toFixed(2) }}</td>
        <td>{{ formatDate(order.tradeTime) }}</td>
        <td>{{ getStatusLabel(order.status) }}</td>
        <td>
          <!-- 恢复订单按钮 -->
          <button
              v-if="order.status === 6"
              @click="handleRestore(order.id)"
              class="restore-btn"
          >
            恢复订单
          </button>

          <!-- 上一步按钮 -->
          <button
              v-if="order.status > 0 && order.status !== 5 && order.status !== 6"
              @click="handlePrevious(order.id)"
          >
            上一步
          </button>

          <!-- 下一步按钮 -->
          <button
              v-if="order.status !== 5 && order.status !== 6"
              @click="handleNextStep(order.id)"
          >
            {{ getNextStepLabel(order.status) }}
          </button>

          <!-- 取消订单按钮 -->
          <button
              v-if="order.status !== 5 && order.status !== 6"
              @click="handleCancel(order.id)"
              class="cancel-btn"
          >
            取消订单
          </button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      search: "",
      statusFilter: "",
      orders: [],
      statusLabels: {
        0: "客户已下单",
        1: "商家已确认",
        2: "已备货",
        3: "已发货",
        4: "已收货",
        5: "已完成",
        6: "取消订单",
      },
      statusMap: {
        "CUSTOMER_ORDERED": 0,
        "MERCHANT_CONFIRMED": 1,
        "STOCK_PREPARED": 2,
        "SHIPPED": 3,
        "RECEIVED": 4,
        "COMPLETED": 5,
        "CANCELLED": 6
      },
      userId: 3, // 根据实际情况设置 userId
    };
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => {
        const matchesSearch =
            (order.id && order.id.toString().includes(this.search)) ||
            (order.customer && order.customer.includes(this.search));

        const matchesStatus = this.statusFilter !== ""
            ? order.status === parseInt(this.statusFilter)
            : true;

        return matchesSearch && matchesStatus;
      });
    },
  },
  mounted() {
    this.fetchOrders(); // 页面加载时获取所有订单数据
  },
  methods: {
    // 格式化日期
    formatDate(datetime) {
      const date = new Date(datetime);
      return date.toLocaleString();
    },

    // 获取所有订单数据
    async fetchOrders() {
      try {
        const response = await axios.get('http://localhost:8080/trades'); // 请求所有订单

        console.log('API 响应:', response.data);

        if (response.data._embedded && Array.isArray(response.data._embedded.trades)) {
          this.orders = response.data._embedded.trades.map(trade => {
            // 从 _links.self.href 中提取订单 ID
            const tradeId = parseInt(trade._links.self.href.split('/').pop());

            // 映射状态字符串到整数
            const mappedStatus = this.statusMap[trade.status] !== undefined
                ? this.statusMap[trade.status]
                : -1;
            const mappedOriginalStatus = trade.originalStatus
                ? (this.statusMap[trade.originalStatus] !== undefined
                    ? this.statusMap[trade.originalStatus]
                    : null)
                : null;

            return {
              id: tradeId,
              customer: `Customer ${trade.customerId}`,
              goodsName: trade.goodsName || `Good ${trade.goodId}`, // 使用商品名称
              productImage: trade.imageUrl || null, // 使用商品图片
              tradeAmount: trade.tradeAmount,
              totalPrice: parseFloat(trade.totalPrice),
              tradeTime: trade.tradeTime,
              status: mappedStatus,
              previousStatus: mappedOriginalStatus
            };
          });
        } else {
          console.error('响应中没有 _embedded.trades 数据');
        }
      } catch (error) {
        console.error('获取订单数据失败', error);
      }
    },

    // 更新订单状态
    async updateOrderStatus(orderId, status) {
      try {
        const response = await axios.put('http://localhost:8080/trades/updateStatus', {
          tradeId: orderId,
          statusCode: status
        });

        if (response.data.status === "success") {
          const order = this.orders.find(o => o.id === orderId);
          if (order) {
            order.status = status;
          }
        } else {
          console.error('更新订单状态失败', response.data.message);
        }
      } catch (error) {
        console.error('更新订单状态请求失败', error);
      }
    },

    // 恢复订单
    async handleRestore(id) {
      try {
        const response = await axios.put(`http://localhost:8080/trades/restore/${id}`);
        if (response.data.status === "success") {
          const order = this.orders.find(o => o.id === id);
          if (order && order.previousStatus !== null) {
            order.status = order.previousStatus; // 恢复订单到上一步的状态
            order.previousStatus = null; // 清除恢复状态的记录
          }
        } else {
          console.error('恢复订单失败', response.data.message);
        }
      } catch (error) {
        console.error('恢复订单请求失败', error);
      }
    },

    // 上一步
    handlePrevious(id) {
      const order = this.orders.find(o => o.id === id);
      if (order) {
        const currentStatus = order.status;
        if (currentStatus > 0) {
          this.updateOrderStatus(id, currentStatus - 1);
        }
      }
    },

    // 下一步
    handleNextStep(id) {
      const order = this.orders.find(o => o.id === id);
      if (order) {
        const currentStatus = order.status;
        if (currentStatus < 5 && currentStatus !== 6) { // 5是已完成，6是已取消
          this.updateOrderStatus(id, currentStatus + 1);
        }
      }
    },

    // 取消订单
    async handleCancel(id) {
      try {
        const response = await axios.put(`http://localhost:8080/trades/seller/cancel/${id}`);
        if (response.data.status === "success") {
          const order = this.orders.find(o => o.id === id);
          if (order) {
            order.previousStatus = order.status; // 记录取消之前的状态
            order.status = 6;  // 设置为取消订单的状态
          }
        } else {
          console.error('取消订单失败', response.data.message);
        }
      } catch (error) {
        console.error('取消订单请求失败', error);
      }
    },

    // 获取状态标签
    getStatusLabel(status) {
      return this.statusLabels[status] || "未知状态";
    },

    // 获取下一步按钮的文本
    getNextStepLabel(status) {
      const nextStepLabels = {
        0: "确认接单",     // 客户下单后，商家确认
        1: "备货完成",     // 商家确认后，备货完成
        2: "开始发货",     // 备货完成后，开始发货
        3: "完成交易",     // 发货后，完成交易
        4: "确认收货",     // 已收货后，确认收货
      };

      return nextStepLabels[status] || "已完成";  // 其他状态不可操作
    }
  }
};
</script>

<style scoped>
/* 统一字体 */
* {
  font-family: 'Arial', sans-serif;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background: #f4f7fc; /* 浅色背景，增加空间感 */
  color: #333;
  padding: 20px;
  font-size: 16px;
}

/* 标题样式 */
h2 {
  color: #2c3e50;
  font-size: 2rem;
  margin-bottom: 30px;
  font-weight: 600;
  text-align: center;
}

/* 过滤区域 */
.filters {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  justify-content: center;
  flex-wrap: wrap;
}

.filters input,
.filters select {
  padding: 10px;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 250px;
  transition: all 0.3s ease;
}

.filters input:focus,
.filters select:focus {
  border-color: #3498db;
  outline: none;
}

/* 表格 */
table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

table th,
table td {
  padding: 15px;
  text-align: center;
  font-size: 1rem;
  color: #34495e;
}

table th {
  background-color: #2c3e50;
  color: #fff;
}

table tr:nth-child(even) {
  background-color: #f9f9f9;
}

table tr:hover {
  background-color: #e1e9f1;
  transition: background-color 0.3s ease;
}

/* 商品图片 */
.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 5px;
}

/* 按钮样式 */
button {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  margin: 5px;
  transition: all 0.3s ease;
}

/* 确认接单按钮 */
button.confirm-btn {
  background-color: #16a085;
  color: #fff;
}

button.confirm-btn:hover {
  background-color: #1abc9c;
}

/* 开始发货按钮 */
button.ship-btn {
  background-color: #f39c12;
  color: #fff;
}

button.ship-btn:hover {
  background-color: #f1c40f;
}

/* 完成交易按钮 */
button.complete-btn {
  background-color: #27ae60;
  color: #fff;
}

button.complete-btn:hover {
  background-color: #2ecc71;
}

/* 取消订单按钮 */
button.cancel-btn {
  background-color: #e74c3c;
  color: #fff;
}

button.cancel-btn:hover {
  background-color: #c0392b;
}

/* 恢复订单按钮 */
button.restore-btn {
  background-color: #3498db;
  color: #fff;
}

button.restore-btn:hover {
  background-color: #2980b9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filters {
    flex-direction: column;
    align-items: center;
  }

  .filters input,
  .filters select {
    width: 100%;
    margin-bottom: 15px;
  }

  table th,
  table td {
    padding: 10px;
    font-size: 0.9rem;
  }

  .product-image {
    width: 40px;
    height: 40px;
  }

  button {
    padding: 6px 12px;
    font-size: 0.9rem;
  }
}
</style>
